<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .box {
      width: 150px;
      height: 150px;
      background-color: #6ff;
      position: absolute;
      left: 0px;
      top: 0px;
    }
  </style>
</head>

<body>
  <div class="box"></div>
</body>
<script>
  // 需求: 盒子跟随鼠标移动   
  // (1)  鼠标移动 => 怎么知道鼠标在哪里移动  移动到了哪个位置?
  // (2)  盒子如何跟随鼠标移动?   margin  translate  position

  var box = document.getElementsByClassName("box")[0];

  var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
  var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

  var maxLeft = clientWidth - box.clientWidth;
  var maxTop = clientHeight - box.clientHeight;

  window.onresize = function () {

    clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
    clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

    maxLeft = clientWidth - box.clientWidth;
    maxTop = clientHeight - box.clientHeight;

  }


  // 鼠标在文档中移动 
  document.onmousemove = function (e) {
    var e = e || window.event;
    console.log(e);
    var x = e.pageX - box.clientWidth / 2;
    var y = e.pageY - box.clientHeight / 2;
    console.log(x, y);

    // 移动之前判断 是否超出临界值 (小于最小值  大于最大值)
    if (x < 0) x = 0;
    if (x > maxLeft) x = maxLeft;
    if (y < 0) y = 0;
    if (y > maxTop) y = maxTop;


    // 取值时记得去单位(200px => 200)  赋值时记得加单位(200px)
    box.style.left = x + "px";
    box.style.top = y + "px";

  }



</script>

</html>